﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace zy_simu.Data
{
    internal class KgStreamConvert
    {
        // 结构体转化为bytes数组流 
        public static byte[] Struct2Bytes(Object strc)
        {
            int size = Marshal.SizeOf(strc);
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr ptr = Marshal.AllocHGlobal(size);
            //将结构体转换为分配好的内存空间
            Marshal.StructureToPtr(strc, ptr, false);
            //Marshal.Copy方法是用来在托管对象（数组）和非托管对象（IntPtr）之间进行内容的复制
            Marshal.Copy(ptr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(ptr);
            return bytes;
        }
        // byte数组流转化为结构体 
        public static T BytesToStuct<T>(byte[] data)
        {
            //得到结构体的大小 
            int size = Marshal.SizeOf(typeof(T));
            //byte数组长度小于结构体的大小 
            if (size > data.Length)
                return default;
            //分配结构体大小的内存空间 
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间 
            Marshal.Copy(data, 0, structPtr, size);
            //将内存空间转换为目标结构体 
            object obj = Marshal.PtrToStructure(structPtr, typeof(T));
            //释放内存空间 
            Marshal.FreeHGlobal(structPtr);
            //返回结构体 
            return (T)obj;
        }
        // bytes流转short数组
        public static short[] BytesToShorts(byte[] data)
        {
            int len = data.Length / 2;
            short[] shorts = new short[len];
            for (int i = 0; i < len; i++)
            {
                shorts[i] = BitConverter.ToInt16(data, i * sizeof(short));
            }
            return shorts;
        }
        // short数组转bytes数组
        public static byte[] ShortsToBytes(short[] data)
        {
            byte[] bytes = new byte[data.Length * 2];
            for (int i = 0; i < data.Length; i++)
            {
                bytes[i * 2] = (byte)(data[i]); 
                bytes[i * 2 + 1] = (byte)(data[i] >> 8);
            }
            return bytes;
        }
        // bytes流转byte二维数组byte[][n]
        public static byte[,] BytesToArray2D(byte[] data, int n_2d)
        {
            int len = data.Length / n_2d;
            byte[,] arr = new byte[len, n_2d];
            for (int i = 0; i < len; i++)
            {
                for(int j = 0; j < n_2d; j++)
                    arr[i, j] = data[i*n_2d + j];
            }
            return arr;
        }
    }
}
